package com.chuantou.yuba.ui.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.FishingCommentTO;
import com.chuantou.yuba.api.to.FishingDetailDataTO;
import com.chuantou.yuba.api.to.FishingTO;
import com.chuantou.yuba.api.to.FishingUserTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.LoginActivity;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.ActivityHelper;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.DateUtil;
import com.chuantou.yuba.util.UiUtil;
import com.chuantou.yuba.util.ViewHolder;

public class FishingDetailFragment extends PaginationListFragment<FishingDetailDataTO> implements OnClickListener {
	private View mHeaderView;
	private NetworkImageView mAvatarView;
	private FishingTO mFishingTO;
	private TextView mNicknameView;
	private TextView mTimeView;
	private TextView mContentView;
	private TextView mFishingTimeView;
	private TextView mFishingLocationView;
	private TextView mFishingCostView;
	private CommentAdapter mAdapter;
	private RecyclerView mRecyclerView;
	private MemberAdapter mMemberAdapter;
	private TextView mJoinView;
	private TextView mFishingUserCntView;
	private List<FishingUserTO> mFishingMembers;
	private View mCommentTagLayout;
	private TextView mCommentTagView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mFishingTO = getArguments().getParcelable(Constants.EXTRA_DATA);
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		View contentView = super.onCreateView(inflater, container, savedInstanceState);
		if (mHeaderView == null) {
			setHasOptionsMenu(true);
			mHeaderView = View.inflate(mContext, R.layout.fishing_detail_header, null);
			mAvatarView = (NetworkImageView) mHeaderView.findViewById(R.id.avatar);
			mAvatarView.setTag(mFishingTO.getUid());
			mAvatarView.setOnClickListener(this);
			mNicknameView = (TextView) mHeaderView.findViewById(R.id.nickname);
			mNicknameView.setOnClickListener(this);
			mNicknameView.setTag(mFishingTO.getUid());
			mTimeView = (TextView) mHeaderView.findViewById(R.id.time);
			mContentView = (TextView) mHeaderView.findViewById(R.id.content);
			mFishingTimeView = (TextView) mHeaderView.findViewById(R.id.fishing_time);
			mFishingLocationView = (TextView) mHeaderView.findViewById(R.id.fishing_location);
			mFishingLocationView.setOnClickListener(this);
			mFishingCostView = (TextView) mHeaderView.findViewById(R.id.fishing_cost);
			mListView.setSelector(new ColorDrawable(Color.TRANSPARENT));
			mListView.setDivider(new ColorDrawable(Color.TRANSPARENT));
			mAdapter = new CommentAdapter();
			mListView.addHeaderView(mHeaderView);
			mListView.setAdapter(mAdapter);
			mRecyclerView = (RecyclerView) mHeaderView.findViewById(R.id.recyclerView);
			LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
			layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
			mRecyclerView.setLayoutManager(layoutManager);
			mMemberAdapter = new MemberAdapter();
			mRecyclerView.setAdapter(mMemberAdapter);
			mJoinView = (TextView) mHeaderView.findViewById(R.id.join);
			mJoinView.setOnClickListener(this);
			mFishingUserCntView = (TextView) mHeaderView.findViewById(R.id.member_count);
			mCommentTagLayout = mHeaderView.findViewById(R.id.comment_tag_layout);
			mCommentTagView = (TextView) mHeaderView.findViewById(R.id.tag);
			setHeaderData(mFishingTO);
			startRequest();
		}
		return contentView;
	}

	public void setHeaderData(FishingTO fishingTO) {
		if (fishingTO == null)
			return;
		BitmapBinder.bindCircularNetImage(mContext, mAvatarView, fishingTO.getAvatar(), R.drawable.default_avatar_round_small);
		mNicknameView.setText(fishingTO.getUsername());
		String time = DateUtils.formatDateTime(mContext, fishingTO.getPublishTime() * 1000, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
				| DateUtils.FORMAT_ABBREV_ALL);
		mTimeView.setText(time);
		mContentView.setText(fishingTO.getContent());
		Date startDate = new Date(fishingTO.getStartTime() * 1000);
		Date endDate = new Date(fishingTO.getEndTime() * 1000);
		String fishingTime = null;
		if (DateUtil.isSameDay(startDate, endDate)) {
			String startTime = DateUtil.getDateString(startDate.getTime(), DateUtil.PATTERN_MDHM);
			String endTime = DateUtil.getDateString(endDate.getTime(), DateUtil.PATTERN_HN);
			fishingTime = startTime + "~" + endTime;
		} else {
			String startTime = DateUtil.getDateString(startDate.getTime(), DateUtil.PATTERN_MDHM);
			String endTime = DateUtil.getDateString(endDate.getTime(), DateUtil.PATTERN_MDHM);
			fishingTime = startTime + "~" + endTime;
		}
		mFishingTimeView.setText(fishingTime);

		int cost = fishingTO.getCost();
		if (cost > 0) {
			mFishingCostView.setText(getString(R.string.fishing_cost_format, cost));
		} else {
			mFishingCostView.setText(R.string.free);
		}
		mFishingLocationView.setText(fishingTO.getAddress());
		if (fishingTO.getMaxPeople() > 0) {
			mFishingUserCntView.setVisibility(View.VISIBLE);
			mFishingUserCntView.setText(String.format("(%d/%d)", fishingTO.getJoinedCount(), fishingTO.getMaxPeople()));
		} else {
			mFishingUserCntView.setVisibility(View.GONE);
		}

	}

	@Override
	protected BaseGsonRequest<FishingDetailDataTO> getRequest(Listener<FishingDetailDataTO> listener, ErrorListener errorListener) {
		String url = UriHelper.getFishingDetailUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		AccountManager accountManager = AccountManager.getInstance(mContext);
		if (accountManager.isLogined()) {
			UserTO user = accountManager.getUserTO();
			params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		}
		params.put(UriHelper.PARAMS_ID, String.valueOf(mFishingTO.getId()));
		params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
		params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		GsonRequest<FishingDetailDataTO> request = new GsonRequest<FishingDetailDataTO>(Method.POST, url, listener, errorListener, params,
				FishingDetailDataTO.class);
		return request;
	}

	@Override
	public void onResponse(FishingDetailDataTO response) {
		super.onResponse(response);
		if (getActivity() != null && response != null) {
			FishingTO fishingTO = response.getFishingTO();
			setHeaderData(fishingTO);
			if (response.getCurrentPage() <= 1) {
				mFishingMembers = response.getFishingUsers();
				if (mFishingMembers == null || mFishingMembers.isEmpty()) {
					mRecyclerView.setVisibility(View.GONE);
				} else {
					mRecyclerView.setVisibility(View.VISIBLE);
					mMemberAdapter.clear();
					mMemberAdapter.add(mFishingMembers);
					mMemberAdapter.notifyDataSetChanged();
				}
				checkHasJoined();
				mAdapter.clear();
				mAdapter.add(new FishingCommentTO());
			}
			List<FishingCommentTO> comments = response.getFishingComments();
			int commentCount = response.getCommentCount();
			if (commentCount > 0) {
				mCommentTagLayout.setVisibility(View.VISIBLE);
				mCommentTagView.setText(Html.fromHtml(getString(R.string.comment_count_tag, commentCount)));
			} else {
				mCommentTagLayout.setVisibility(View.GONE);
			}
			mAdapter.add(comments);
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		checkHasJoined();
	}

	private synchronized void checkHasJoined() {
		AccountManager accountManager = AccountManager.getInstance(mContext);
		if (accountManager.isLogined()) {
			boolean hasJoined = false;
			if (mFishingMembers != null && !mFishingMembers.isEmpty()) {
				UserTO loginUser = accountManager.getUserTO();
				for (FishingUserTO user : mFishingMembers) {
					if (loginUser.getUid() == user.getUid()) {
						hasJoined = true;
						break;
					}
				}
			}
			if (hasJoined) {
				mJoinView.setEnabled(false);
				mJoinView.setText(R.string.has_joined);
			} else {
				mJoinView.setEnabled(true);
				mJoinView.setText(R.string.sign_up);
			}
		} else {
			mJoinView.setEnabled(true);
			mJoinView.setText(R.string.sign_up);
		}
		if (mFishingTO.getMaxPeople() > 0) {
			if (mFishingMembers != null && mFishingMembers.size() >= mFishingTO.getMaxPeople()) {
				mJoinView.setEnabled(false);
				mJoinView.setText(R.string.sign_up_full);
			}
		}
	}

	@Override
	protected String getEmptyString() {
		return mContext.getString(R.string.no_content);
	}

	public void reload() {
		load(1);
	}

	private class MemberAdapter extends RecyclerView.Adapter<MemberHolder> {
		private List<FishingUserTO> mMembers = new ArrayList<FishingUserTO>();

		@Override
		public int getItemCount() {
			return mMembers.size();
		}

		public void add(List<FishingUserTO> users) {
			if (users != null && !users.isEmpty()) {
				mMembers.addAll(users);
			}
		}

		public void add(FishingUserTO user) {
			mMembers.add(user);
		}

		public void clear() {
			mMembers.clear();
		}

		@Override
		public void onBindViewHolder(MemberHolder holder, int position) {
			FishingUserTO user = mMembers.get(position);
			BitmapBinder.bindCircularNetImage(mContext, holder.mAvatarView, user.getAvatar(), R.drawable.default_avatar_round_small);
			holder.mAvatarView.setTag(user.getUid());
		}

		@Override
		public MemberHolder onCreateViewHolder(ViewGroup parent, int position) {
			View view = View.inflate(parent.getContext(), R.layout.fishing_user_item, null);
			return new MemberHolder(view);
		}

	}

	class MemberHolder extends RecyclerView.ViewHolder {
		private NetworkImageView mAvatarView;

		public MemberHolder(View itemView) {
			super(itemView);
			mAvatarView = (NetworkImageView) itemView.findViewById(R.id.avatar);
			mAvatarView.setScaleType(ScaleType.FIT_CENTER);
			mAvatarView.setOnClickListener(FishingDetailFragment.this);
		}

		public ImageView getImageView() {
			return mAvatarView;
		}
	}

	class CommentAdapter extends BaseAdapter {
		private List<FishingCommentTO> mComments = new ArrayList<FishingCommentTO>();

		public void add(FishingCommentTO comment) {
			this.mComments.add(comment);
		}

		public void add(List<FishingCommentTO> comments) {
			if (comments != null && !comments.isEmpty()) {
				this.mComments.addAll(comments);
			}
		}

		public void clear() {
			this.mComments.clear();
		}

		@Override
		public int getCount() {
			return mComments.size();
		}

		@Override
		public Object getItem(int position) {
			return mComments.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public int getItemViewType(int position) {
			return position == 0 ? 0 : 1;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int viewType = getItemViewType(position);
			if (viewType == 0) {
				if (convertView == null) {
					convertView = new View(mContext);
					convertView.setBackgroundColor(Color.TRANSPARENT);
				}
			} else {
				if (convertView == null) {
					convertView = View.inflate(mContext, R.layout.news_detail_item_comment, null);
				}
				FishingCommentTO commentTO = mComments.get(position);
				NetworkImageView avatarView = ViewHolder.get(convertView, R.id.avatar);
				avatarView.setTag(commentTO.getUid());
				avatarView.setOnClickListener(FishingDetailFragment.this);
				BitmapBinder.bindCircularNetImage(mContext, avatarView, commentTO.getAvatar(), R.drawable.default_avatar_round_small);
				TextView nickNameView = ViewHolder.get(convertView, R.id.nickname);
				nickNameView.setTag(commentTO.getUid());
				nickNameView.setOnClickListener(FishingDetailFragment.this);
				nickNameView.setText(commentTO.getUsername());
				TextView timeView = ViewHolder.get(convertView, R.id.time);
				String time = DateUtils.formatDateTime(mContext, commentTO.getCommentTime() * 1000, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
						| DateUtils.FORMAT_ABBREV_ALL);
				timeView.setText(time);
				TextView commentView = ViewHolder.get(convertView, R.id.comment);
				commentView.setText(commentTO.getContent());
			}
			return convertView;
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.nickname:
		case R.id.avatar:
			Object tag = v.getTag();
			if (tag != null) {
				String tagString = String.valueOf(tag);
				if (TextUtils.isDigitsOnly(tagString)) {
					ActivityHelper.toProfileActivity(getActivity(), Long.parseLong(tagString));
				}
			}
			break;
		case R.id.join:
			if (UiUtil.isFastDoubleClick())
				return;
			joinFishing();
			break;
		case R.id.fishing_location:
			String location = mFishingTO.getLocation();
			if(TextUtils.isEmpty(location))
				return;
			String lat = "0";
			String lng = "0";
			if (!TextUtils.isEmpty(location) && location.contains(",")) {
				String[] array = location.split(",");
				lat = array[1];
				lng = array[0];
			}
			String point = lat + "," + lng;
			String label = mFishingTO.getAddress();
			String uriBegin = "geo:" + point;
			String query = point + "(" + label + ")";
			String encodedQuery = Uri.encode(query);
			String uriString = uriBegin + "?q=" + encodedQuery;
			Uri uri = Uri.parse(uriString);
			Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
			if (UiUtil.isIntentAvailable(mContext, intent)) {
				startActivity(intent);
			} else {
				Toast.makeText(mContext, R.string.no_navi_app_installed, Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
	}

	private void joinFishing() {
		mJoinView.setEnabled(false);
		mJoinView.setText(R.string.sign_up_ing);
		AccountManager manager = AccountManager.getInstance(mContext);
		if (manager.isLogined()) {
			final UserTO user = manager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			} else {
				String requestUrl = UriHelper.getJoinFishingUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_ID, String.valueOf(mFishingTO.getId()));
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, requestUrl, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (getActivity() != null) {
							if (response != null) {
								if (response.isSuccess()) {
									Toast.makeText(mContext, R.string.sign_up_success, Toast.LENGTH_SHORT).show();
									if (mFishingMembers == null) {
										mFishingMembers = new ArrayList<FishingUserTO>();
									}
									FishingUserTO member = new FishingUserTO();
									member.setAvatar(user.getAvatar());
									member.setJoinedTime(System.currentTimeMillis() / 1000);
									member.setNickname(user.getUsername());
									member.setSex(user.getSex());
									member.setUid(user.getUid());
									mFishingMembers.add(member);
									mMemberAdapter.add(member);
									mRecyclerView.setVisibility(View.VISIBLE);
									mMemberAdapter.notifyDataSetChanged();
									if (mFishingTO.getMaxPeople() > 0) {
										mFishingUserCntView.setVisibility(View.VISIBLE);
										mFishingUserCntView.setText(String.format("(%d/%d)", mFishingTO.getJoinedCount() + 1, mFishingTO.getMaxPeople()));
									} else {
										mFishingUserCntView.setVisibility(View.GONE);
									}
									checkHasJoined();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										msg = TextUtils.isEmpty(msg) ? getString(R.string.sign_up_failed) : msg;
										Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(mContext, R.string.sign_up_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (getActivity() != null) {
							checkHasJoined();
							Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(mContext, request);
			}
		} else {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
		}
	}
}
